"""
Utility function to analyze text for typos and semantic issues.
"""
from .call_llm import call_llm
import json
from .tools import format_json_response

def text_analysis(inspector_text, title=""):
    """
    Analyze text for typos and semantic confusion.
    
    Args:
        text (str): Text to analyze, typically the inspector field
        
    Returns:
        dict: Analysis results with keys for typos and semantic issues
    """
    if not inspector_text or not isinstance(inspector_text, str):
        return {"typo_issues": [], "semantic_issues": []}
    
    # Create prompt for LLM to analyze the text
    prompt = f"""
请以技术文档审校标准，分析评估报告中针对被评估系统的描述文本是否存在错别字或语义混乱问题。注意：
1. 核心原则：文本须严格保持 **第三方中立视角**（如使用“本业务系统”“该系统”等指代被评估对象，禁止混用“我们”等第一人称）。
2. 语义混乱重点检查项：
   视角一致性：是否始终用“该系统/此系统/其”等第三人称指代被评估对象（错误例：混用“我们系统”和“本业务系统”）。
   术语准确性：系统名称、模块名、功能名是否全文统一（如“用户管理模块”在全文表述无歧义）。
   逻辑清晰性：因果关系、操作流程是否无歧义（例：“点击提交按钮后数据入库”完整，而非“点击后即可”）。
3. 错别字检查规则：
   仅报告影响专业性的明显错误（如“界⾯”→“界面”、“账⼾”→“账户”），忽略不影响理解的通用缩写（如“登录”vs“登陆”暂不强制修改）。
4.  注意事项：
    *   只报告**确认有问题**且**影响较大**的项目。
    *   对于次要、主观或存疑的问题**忽略不报**。
    *   避免过度解读或过度修改。

"{inspector_text}"

请以JSON格式返回分析结果，格式如下：
{{
  "typo_issues": [
    {{
      "type": "typo",
      "severity": "high/medium/low",
      "description": "错别字问题描述",
      "suggestion": "改进建议"
    }}
  ],
  "semantic_issues": [
    {{
      "type": "semantic",
      "severity": "high/medium/low",
      "description": "语义混乱问题描述",
      "suggestion": "改进建议"
    }}
  ]
}}

如果没有发现问题，请返回空列表。请确保返回的是有效的JSON格式。
"""
    
    # Call LLM to analyze the text
    response = call_llm(prompt)
    print("response: ",response)
    # Format and parse the response
    formatted_response = format_json_response(response)
    print("formatted_response: ",formatted_response)
    try:
        result = json.loads(formatted_response)
        # Ensure the result has the expected structure
        if not isinstance(result, dict):
            result = {"typo_issues": [], "semantic_issues": []}
        if "typo_issues" not in result:
            result["typo_issues"] = []
        if "semantic_issues" not in result:
            result["semantic_issues"] = []
            
        # Add title and originalContent to each issue
        for issue_type in ["typo_issues", "semantic_issues"]:
            for issue in result[issue_type]:
                issue["title"] = title
                issue["originalContent"] = inspector_text
    except json.JSONDecodeError:
        print("formatted_response: ",formatted_response)
        print("LLM response is not valid JSON")
        # If LLM response is not valid JSON, return empty results
        result = {"typo_issues": [], "semantic_issues": []}
    
    return result

if __name__ == "__main__":
    # Test with sample text
    test_text = "这是一个测试文本，包含一些错别宇和语意混乱的内容。"
    test_title = "测试标题"
    result = text_analysis(test_text, test_title)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    
    # Test the format_json_response function
    test_json = '''```json
{
  "typo_issues": [
    {
      "type": "typo",
      "severity": "high",
      "description": "\"休电脑错别字\"中的\"休\"可能是\"修\"的错别字。",
      "suggestion": "将\"休\"改为\"修\"。"
    }
  ],
  "semantic_issues": [
    {
      "type": "semantic",
      "severity": "high",
      "description": "\"午觉睡月亮\"语义混乱，午觉通常指白天睡觉，而\"睡月亮\"不符合常规表达。",
      "suggestion": "改为\"午觉睡过头\"或\"晚上看月亮\"等符合逻辑的表达。"
    }
  ]
}```'''
    formatted = format_json_response(test_json)
    print("\nFormatted JSON:\n", formatted)
    print("\nParsed result:\n", json.loads(formatted))
